package ru.bragnikita.utils.test.nio;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.io.filefilter.FileFilterUtils;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * @author Nikita.Brazhnikov
 */
public class ParallelWriteLogAndRead {

	private static final Logger logger = Logger.getLogger(ParallelWriteLogAndRead.class.getName());

	public static void main(String[] args) {
		logger.log(Level.INFO, "Start");
		File targetFile = FileUtils.listFiles(new File(".iotest"), FileFilterUtils.prefixFileFilter("log"))
		Thread writeThread = new Thread(new Runnable() {
			@Override
			public void run() {
				FileWriter writer = null;
				try {
					writer = new FileWriter(targetFile, true);
					int recordNumber = 0;
					while (!Thread.interrupted()) {
						writer.write("Record #" + recordNumber + "\n");
						recordNumber++;
						writer.flush();
						Thread.sleep(1000l);

						if (recordNumber == 5) {
							IOUtils.closeQuietly(writer);
							Path oldP = targetFile.toPath();
							Path newP = new File("logfile_old.txt").toPath();
							Files.move(oldP, newP.resolveSibling(newP));
							targetFile.createNewFile();
							writer = new FileWriter(targetFile, true);
						}
					}
				} catch (IOException e) {
					e.printStackTrace();
				} catch (InterruptedException e) {
					System.err.println("Writer was interrupted");
				} finally {
					IOUtils.closeQuietly(writer);
				}
			}
		}, "Writer");
	}
}
